"""
Edge 书签整理工具

功能概述：
1. 读取Edge浏览器本地书签文件
2. 自动整理书签：去重、分类、统计
3. 生成整理后的HTML书签文件
4. 备份原始书签文件
5. 将整理后的书签导入回Edge浏览器

主要处理流程：
1. 读取原始书签数据并解析JSON结构
2. 递归遍历提取所有书签信息
3. 排序去重（保留最新条目）
4. 分析域名并分类整理
5. 生成层级目录结构
6. 输出整理后的书签文件
7. 安全替换原始书签文件（含备份）

注意事项：
- 需要关闭Edge浏览器后运行
- 会自动备份原始书签文件
- 需要管理员确认操作
"""

import json
import os
import shutil
import uuid
import time
from datetime import datetime
from urllib.parse import urlparse
from collections import defaultdict

# --------------------------
# 配置区域
# --------------------------
BOOKMARKS_PATH = os.path.expanduser(
    '~\\AppData\\Local\\Microsoft\\Edge\\User Data\\Default\\Bookmarks')
OUTPUT_HTML = 'edge_bookmarks_out.html'

# --------------------------
# 核心功能函数
# --------------------------


def load_bookmarks(file_path):
    """读取并解析Edge书签文件"""
    with open(file_path, 'r', encoding='utf-8') as f:
        return json.load(f)


def extract_bookmark_info(bookmark_data):
    """
    递归提取书签信息
    返回结构：[{name, url, date_added}]
    """
    results = []

    def traverse(node):
        if 'children' in node:  # 当前是文件夹节点
            for child in node['children']:
                traverse(child)
        elif node.get('type') == 'url':  # 当前是书签节点
            results.append({
                'name': node.get('name'),
                'url': node.get('url'),
                'date_added': int(node.get('date_added', 0))
            })
    # 遍历所有根目录：书签栏/其他书签/同步书签
    for root in ['bookmark_bar', 'other', 'synced']:
        traverse(bookmark_data['roots'][root])
    return results


def process_bookmarks(original_data):
    """
    处理书签数据流程：
    1. 按URL排序 → 2. 去重保留最新 → 3. 提取域名 →
    4. 统计数量 → 5. 分类 → 6. 最终排序
    """
    # 去重处理：相同URL保留最新(date_added最大)
    sorted_by_url = sorted(original_data, key=lambda x: x['url'])
    unique_bookmarks = {}
    for item in sorted_by_url:
        url = item['url']
        if url not in unique_bookmarks or item['date_added'] > unique_bookmarks[url]['date_added']:
            unique_bookmarks[url] = item

    # 添加域名信息
    deduped_list = list(unique_bookmarks.values())
    for item in deduped_list:
        parsed = urlparse(item['url'])
        item['web'] = parsed.netloc  # 提取完整域名

    # 统计域名出现次数
    domain_counter = defaultdict(int)
    for item in deduped_list:
        domain_counter[item['web']] += 1

    # 分类逻辑：单次出现的归类到"常用"，多次的按域名分类
    processed = []
    for item in deduped_list:
        count = domain_counter[item['web']]
        item['web_qty'] = count
        item['dir'] = '常用' if count == 1 else item['web']
        processed.append(item)

    # 最终排序：先分类目录，再按添加时间排序
    return sorted(processed,
                 key=lambda x: (x['dir'] != '常用', x['dir'], -x['date_added']))


def generate_html_bookmarks(bookmark_list, output_file):
    """生成浏览器可导入的HTML书签文件"""
    html_template = """<!DOCTYPE NETSCAPE-Bookmark-file-1>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
<TITLE>整理后的书签</TITLE>
<H1>书签整理结果</H1>
<DL><p>
{content}
</DL>"""

    folder_content = []
    current_dir = None
    for item in bookmark_list:
        if item['dir'] != current_dir:
            if current_dir is not None:  # 关闭前一个目录
                folder_content.append("</DL><p>")
            # 添加新目录标题
            folder_content.append(f'<DT><H3>{item["dir"]}</H3>\n<DL><p>')
            current_dir = item['dir']
        # 添加书签条目
        folder_content.append(
            f'<DT><A HREF="{item["url"]}">{item["name"]}</A>')

    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(html_template.format(content='\n'.join(folder_content)))


def backup_original_bookmarks(original_path):
    """创建带时间戳的备份文件"""
    backup_name = f"{original_path}.bak{datetime.now().strftime('%Y%m%d%H%M%S')}"
    shutil.copy2(original_path, backup_name)
    return backup_name


def replace_system_bookmarks(original_path, new_data):
    """安全替换系统书签文件"""
    # 清空现有书签
    with open(original_path, 'w', encoding='utf-8') as f:
        json.dump({
            "version": 1,
            "roots": {
                "bookmark_bar": {"children": [], "id": "1", "name": "书签栏", "type": "folder"},
                "other": {"children": [], "id": "2", "name": "其他书签", "type": "folder"},
                "synced": {"children": [], "id": "3", "name": "移动设备书签", "type": "folder"}
            }
        }, f, ensure_ascii=False)

    # 构建新书签结构
    new_structure = {
        "version": 1,
        "roots": {
            "bookmark_bar": {"children": [], "id": "1", "name": "书签栏", "type": "folder"},
            "other": {"children": [], "id": "2", "name": "其他书签", "type": "folder"},
            "synced": {"children": [], "id": "3", "name": "移动设备书签", "type": "folder"}
        }
    }

    # 按分类构建文件夹结构
    folders = {'常用': new_structure['roots']['bookmark_bar']['children']}
    for item in new_data:
        if item['dir'] not in folders and item['dir'] != '常用':
            new_folder = {
                "children": [],
                "id": str(uuid.uuid4()),
                "name": item['dir'],
                "type": "folder"
            }
            new_structure['roots']['other']['children'].append(new_folder)
            folders[item['dir']] = new_folder['children']

    # 添加书签条目
    for item in new_data:
        folders[item['dir']].append({
            "type": "url",
            "id": str(uuid.uuid4()),
            "name": item["name"],
            "url": item["url"],
            "date_added": str(int(time.time() * 1000000))  # 使用当前时间戳
        })

    # 写入新书签文件
    with open(original_path, 'w', encoding='utf-8') as f:
        json.dump(new_structure, f, ensure_ascii=False, indent=2)


# --------------------------
# 主程序流程
# --------------------------
if __name__ == "__main__":
    # 读取原始数据
    original = load_bookmarks(BOOKMARKS_PATH)
    all_bookmarks = extract_bookmark_info(original)

    # 数据处理
    processed_bookmarks = process_bookmarks(all_bookmarks)

    # 生成HTML备份
    generate_html_bookmarks(
        [{'dir': b['dir'], 'name': b['name'], 'url': b['url']} for b in processed_bookmarks],
        OUTPUT_HTML
    )

    # 备份并替换系统书签
    backup_path = backup_original_bookmarks(BOOKMARKS_PATH)
    print(f"已创建备份文件：{backup_path}")

    # 用户确认
    confirm = input("是否要替换系统书签？(y/n): ").lower()
    if confirm == 'y':
        replace_system_bookmarks(BOOKMARKS_PATH, processed_bookmarks)
        print("书签已成功更新！请重启Edge浏览器查看效果")
    else:
        print("已保留原始书签文件，仅生成整理后的HTML备份")